﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sharp.Infrastructure
{
    internal static class ClientExceptionHelper
    {
        internal static void ThrowIfNegative(int value, string parameterName)
        {
            if (value < 0)
            {
                throw new ArgumentOutOfRangeException(parameterName, value, "Value for this parameter must be equal or greater than zero.");
            }
        }

        internal static void ThrowIfNull(object parameter, string name)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(name);
            }
        }

        internal static void ThrowIfNullOrEmpty(string parameter, string name)
        {
            if (string.IsNullOrEmpty(parameter))
            {
                throw new ArgumentNullException(name);
            }
        }

        internal static void ThrowIfGuidEmpty(Guid parameter, string name)
        {
            if (parameter == Guid.Empty)
            {
                throw new ArgumentException("Expected non-empty Guid.", name);
            }
        }

        internal static string FormatMessage(int errorCode, params object[] arguments)
        {
            string text = errorCode.ToString(CultureInfo.InvariantCulture);
            string result;
            try
            {
                result = string.Format(CultureInfo.InvariantCulture, text, arguments);
            }
            catch (FormatException)
            {
                StringBuilder stringBuilder = new StringBuilder(text);
                for (int i = 0; i < arguments.Length; i++)
                {
                    stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, "\nData[{0}] = \"{1}\"", new object[]
                    {
                        i,
                        arguments[i]
                    }));
                }
                result = stringBuilder.ToString();
            }
            return result;
        }

        internal static void Assert(bool condition, string message, params object[] args)
        {
            ClientExceptionHelper.Assert(condition, string.Format(CultureInfo.InvariantCulture, message, args));
        }

        internal static void Assert(bool condition, string message)
        {
            InvalidOperationException ex = null;
            if (!condition)
            {
                ex = new InvalidOperationException(message);
            }
            if (ex != null)
            {
                throw ex;
            }
        }
    }
}
